import 'package:flutter/material.dart';
import 'package:get/get.dart';
import 'index.dart';
import '../../../common/models/server_model.dart';

class HomeIndexPage extends GetView<HomeIndexController> {
  const HomeIndexPage({super.key});

  @override
  Widget build(BuildContext context) {
    return Scaffold(
      appBar: AppBar(
        title: const Text('服务器列表'),
        elevation: 0,
        automaticallyImplyLeading: false, // 首页无返回按钮
        actions: [
          // 分组管理按钮
          IconButton(
            icon: const Icon(Icons.folder_outlined),
            onPressed: controller.showGroupManagement,
            tooltip: '分组管理',
          ),
          // 添加服务器按钮
          IconButton(
            icon: const Icon(Icons.add),
            onPressed: controller.showAddServerForm,
            tooltip: '添加服务器',
          ),
          const SizedBox(width: 8),
        ],
      ),
      body: RefreshIndicator(
        onRefresh: controller.onRefresh,
        child: Obx(() {
          final hasServers = controller.servers.isNotEmpty;
          final hasGroups = controller.groups.isNotEmpty;
          
          if (!hasServers) {
            return _buildEmptyView();
          }

          return ListView(
            padding: const EdgeInsets.all(12), // 紧凑内边距：16 -> 12
            children: [
              // 分组列表
              if (hasGroups) ...[
                ...controller.groups.map((group) {
                  return _buildGroupSection(group);
                }),
              ],
              // 未分组服务器
              if (controller.getUngroupedServers().isNotEmpty) ...[
                if (hasGroups) const SizedBox(height: 8),
                _buildUngroupedSection(),
              ],
            ],
          );
        }),
      ),
    );
  }

  /// 构建分组区域
  Widget _buildGroupSection(ServerGroup group) {
    final servers = controller.getServersByGroup(group.id);
    
    if (servers.isEmpty) {
      return const SizedBox.shrink();
    }
    
    return Obx(() {
      final isExpanded = controller.groupExpandedStates[group.id] ?? true;
      final connectedCount = servers.where((s) => s.status == ServerStatus.connected).length;
      
      return Container(
        margin: const EdgeInsets.only(bottom: 10), // 紧凑间距：12 -> 10
        child: Card(
          elevation: 2,
          shape: RoundedRectangleBorder(borderRadius: BorderRadius.circular(12)),
          child: Column(
            children: [
              // 分组头部（可点击展开/折叠）
              InkWell(
                onTap: () => controller.toggleGroupExpanded(group.id),
                borderRadius: const BorderRadius.only(
                  topLeft: Radius.circular(12),
                  topRight: Radius.circular(12),
                ),
                child: Container(
                  padding: const EdgeInsets.symmetric(horizontal: 12, vertical: 10), // 紧凑内边距
                  decoration: BoxDecoration(
                    color: Colors.blue[50],
                    borderRadius: BorderRadius.only(
                      topLeft: const Radius.circular(12),
                      topRight: const Radius.circular(12),
                      bottomLeft: isExpanded ? Radius.zero : const Radius.circular(12),
                      bottomRight: isExpanded ? Radius.zero : const Radius.circular(12),
                    ),
                  ),
                  child: Row(
                    children: [
                      // 展开/折叠图标
                      Icon(
                        isExpanded ? Icons.keyboard_arrow_down : Icons.keyboard_arrow_right,
                        size: 20, // 紧凑图标：24 -> 20
                        color: Colors.blue[700],
                      ),
                      const SizedBox(width: 8),
                      // 分组图标
                      Icon(Icons.folder, size: 20, color: Colors.blue[700]),
                      const SizedBox(width: 8),
                      // 分组名称和服务器数量
                      Expanded(
                        child: Column(
                          crossAxisAlignment: CrossAxisAlignment.start,
                          children: [
                            Text(
                              group.name,
                              style: TextStyle(
                                fontSize: 14, // 紧凑字体：15 -> 14
                                fontWeight: FontWeight.bold,
                                color: Colors.blue[900],
                              ),
                            ),
                            if (group.description != null && group.description!.isNotEmpty)
                              Text(
                                group.description!,
                                style: TextStyle(fontSize: 10, color: Colors.blue[600]),
                                maxLines: 1,
                                overflow: TextOverflow.ellipsis,
                              ),
                          ],
                        ),
                      ),
                      // 服务器数量和状态
                      Column(
                        crossAxisAlignment: CrossAxisAlignment.end,
                        children: [
                          Text(
                            '${servers.length} 台',
                            style: TextStyle(
                              fontSize: 11, // 紧凑字体：12 -> 11
                              color: Colors.blue[700],
                              fontWeight: FontWeight.w600,
                            ),
                          ),
                          if (connectedCount > 0)
                            Text(
                              '$connectedCount 在线',
                              style: TextStyle(
                                fontSize: 10, // 紧凑字体：11 -> 10
                                color: Colors.green[600],
                              ),
                            ),
                        ],
                      ),
                    ],
                  ),
                ),
              ),
              
              // 展开的服务器列表
              if (isExpanded) ...[
                ...servers.asMap().entries.map((entry) {
                  final index = entry.key;
                  final server = entry.value;
                  final isLast = index == servers.length - 1;
                  return Padding(
                    padding: EdgeInsets.fromLTRB(10, 10, 10, isLast ? 10 : 0), // 紧凑内边距
                    child: _buildServerCard(server, compact: true),
                  );
                }),
              ],
            ],
          ),
        ),
      );
    });
  }

  /// 构建未分组区域
  Widget _buildUngroupedSection() {
    final servers = controller.getUngroupedServers();
    
    return Column(
      crossAxisAlignment: CrossAxisAlignment.start,
      children: [
        Padding(
          padding: const EdgeInsets.only(left: 4, bottom: 8),
          child: Row(
            children: [
              Icon(Icons.widgets_outlined, size: 16, color: Colors.grey[600]),
              const SizedBox(width: 6),
              Text(
                '默认分组 (${servers.length})',
                style: TextStyle(
                  fontSize: 13, // 紧凑字体
                  fontWeight: FontWeight.bold,
                  color: Colors.grey[700],
                ),
              ),
            ],
          ),
        ),
        ...servers.asMap().entries.map((entry) {
          final index = entry.key;
          final server = entry.value;
          return Padding(
            padding: EdgeInsets.only(bottom: index == servers.length - 1 ? 0 : 8),
            child: _buildServerCard(server),
          );
        }),
      ],
    );
  }

  /// 构建空视图
  Widget _buildEmptyView() {
    return ListView(
      padding: const EdgeInsets.all(16),
      children: [
        const SizedBox(height: 60),
        Center(
          child: Column(
            mainAxisAlignment: MainAxisAlignment.center,
            children: [
              Icon(
                Icons.dns_outlined,
                size: 80,
                color: Colors.grey[300],
              ),
              const SizedBox(height: 20),
              Text(
                '还没有服务器',
                style: TextStyle(
                  fontSize: 18,
                  color: Colors.grey[600],
                ),
              ),
              const SizedBox(height: 10),
              Text(
                '点击右上角 + 添加第一台服务器',
                style: TextStyle(
                  fontSize: 14,
                  color: Colors.grey[400],
                ),
              ),
            ],
          ),
        ),
      ],
    );
  }

  /// 构建服务器卡片
  Widget _buildServerCard(ServerModel server, {bool compact = false}) {
    return Card(
      margin: EdgeInsets.zero,
      elevation: compact ? 1 : 2,
      shape: RoundedRectangleBorder(
        borderRadius: BorderRadius.circular(compact ? 8 : 12),
      ),
      child: InkWell(
        onTap: () => controller.openServerDetail(server),
        onLongPress: () => controller.showEditServerForm(server),
        borderRadius: BorderRadius.circular(compact ? 8 : 12),
        child: Padding(
          padding: EdgeInsets.all(compact ? 10 : 12), // 紧凑内边距
          child: Column(
            crossAxisAlignment: CrossAxisAlignment.start,
            children: [
              // 标题行
              Row(
                children: [
                  // 状态指示器
                  Container(
                    width: compact ? 8 : 10,
                    height: compact ? 8 : 10,
                    decoration: BoxDecoration(
                      shape: BoxShape.circle,
                      color: _getStatusColor(server.status),
                    ),
                  ),
                  SizedBox(width: compact ? 8 : 10),
                  // 服务器名称
                  Expanded(
                    child: Text(
                      server.name,
                      style: TextStyle(
                        fontSize: compact ? 13 : 14, // 紧凑字体
                        fontWeight: FontWeight.bold,
                      ),
                      maxLines: 1,
                      overflow: TextOverflow.ellipsis,
                    ),
                  ),
                  SizedBox(width: compact ? 6 : 8),
                  // 状态徽章
                  Container(
                    padding: EdgeInsets.symmetric(
                      horizontal: compact ? 6 : 8,
                      vertical: compact ? 2 : 3,
                    ),
                    decoration: BoxDecoration(
                      color: _getStatusColor(server.status).withOpacity(0.1),
                      borderRadius: BorderRadius.circular(8),
                    ),
                    child: Text(
                      server.status.displayName,
                      style: TextStyle(
                        fontSize: 10, // 紧凑字体
                        color: _getStatusColor(server.status),
                        fontWeight: FontWeight.w600,
                      ),
                    ),
                  ),
                ],
              ),
              SizedBox(height: compact ? 6 : 8),
              // 连接信息
              Row(
                children: [
                  Icon(Icons.dns, size: compact ? 14 : 16, color: Colors.grey[600]),
                  const SizedBox(width: 6),
                  Expanded(
                    child: Text(
                      server.connectionString,
                      style: TextStyle(
                        fontSize: compact ? 11 : 12, // 紧凑字体
                        color: Colors.grey[600],
                      ),
                      maxLines: 1,
                      overflow: TextOverflow.ellipsis,
                    ),
                  ),
                ],
              ),
              if (server.lastConnectedAt != null) ...[
                SizedBox(height: compact ? 4 : 6),
                Row(
                  children: [
                    Icon(Icons.access_time, size: compact ? 14 : 16, color: Colors.grey[500]),
                    const SizedBox(width: 6),
                    Text(
                      '最后连接: ${_formatTime(server.lastConnectedAt!)}',
                      style: TextStyle(
                        fontSize: compact ? 10 : 11, // 紧凑字体
                        color: Colors.grey[500],
                      ),
                    ),
                  ],
                ),
              ],
            ],
          ),
        ),
      ),
    );
  }

  /// 获取状态颜色
  Color _getStatusColor(ServerStatus status) {
    switch (status) {
      case ServerStatus.connected:
        return Colors.green;
      case ServerStatus.connecting:
        return Colors.orange;
      case ServerStatus.error:
        return Colors.red;
      case ServerStatus.disconnected:
        return Colors.grey;
    }
  }

  /// 格式化时间
  String _formatTime(DateTime dateTime) {
    final now = DateTime.now();
    final difference = now.difference(dateTime);

    if (difference.inMinutes < 1) {
      return '刚刚';
    } else if (difference.inHours < 1) {
      return '${difference.inMinutes} 分钟前';
    } else if (difference.inDays < 1) {
      return '${difference.inHours} 小时前';
    } else if (difference.inDays < 7) {
      return '${difference.inDays} 天前';
    } else {
      return '${dateTime.month}-${dateTime.day}';
    }
  }
}

